var createBtn = function(){
	$('.scroll-top').click(function () {
		$('body,html').animate({scrollTop: 0}, 500);
		return false;
	});
}

var scrollFx = function(){
	var _scrollTop = $(window).scrollTop();
	if($(".wrap .content-wrap").hasClass("support")){
		if(_scrollTop > 345 ){
			$(".navi").css({"position":"fixed", "top":"0"});
			$(".navi").addClass('fix');
		} else {
			$(".navi").css({"position":"absolute", "top":"345px"});
			$(".navi").removeClass('fix');
		}
	}
}


///////////
var _winH;
var _winW;
var _gnbW = 260;

function checkEmpty(v) {
	var t = v.replace(/\s|銆€/gi, '');
	return t;
}

function checkMail(t) {
	var regex = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
	return regex.test(t);
}

function goUrl(u) {
	window.location = u;
}

function openUrl(u) {
	window.open(u, '_blank');
}

function getUrlParameter(name) {
    name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
    var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
    var results = regex.exec(location.search);
    return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
}
/**
 * screen0的屏幕适配
 */
function loadFx(){
	_winH = document.body.clientHeight; 
	_winW = document.body.clientHeight;
	$(".home.content-wrap .screen0").css("height",_winH+"px");
	$(".home.content-wrap .screen0 .marginC").css("height",(_winH-80)+"px");
	screenResizeFx( -parseInt($(".wrap").css("margin-right")) );
}

function screenResizeFx($now){
	$(".wrap").css({"margin-right":-$now+"px"});
	var val = ($now/_gnbW)*32;
	$(".header-wrap .link").css({"margin-right":val+"px"});

	var wrapW =($(".header-wrap .wrap-holder").width() - $now ) - _winW;

	if( wrapW > 1){
		$(".blank").css("width", _winW+wrapW );
	} else {
		$(".blank").css("width", 0 );
	}
	if( $(".wrap .content-wrap").hasClass("home")){
		circleFx();
	};
}

function createMenu() {
	$(".gnb .btn").click(function(){
		var _parent = $(this).parent();
		$(".root").toggleClass( "open" );
		var _isOpen =  $(".root").hasClass("open") ? true : false;

		_parent.find(".bg").css("borderSpacing", 0);
		_parent.find(".bg").stop().animate({  borderSpacing: 1 }, {
			step: function(now,fx) {
				_now = _isOpen ? -now*_gnbW : -_gnbW+now*_gnbW;
				$(this).css({'transform':'matrix(1,0,0,1,'+_now+',0)',
							'-webkit-transform':'matrix(1,0,0,1,'+_now+',0)',
							'-moz-transform':'matrix(1,0,0,1,'+_now+',0)'
				});

				screenResizeFx(_now);

			},duration:500,
			easing :'easeInOutCubic',
			complete: function(){

			}
		});
		if(_isOpen) {
			sessionStorage.setItem("menu", "open");
		} else {
			sessionStorage.setItem("menu", "close");
		}
	});

	$(".header-wrap .page li").click(function(){
		switch( $(this).attr("class") ) {
			case "wp":
				var _wp='<div class="wpaper">'+
					'<p class="subTitle">Whitepaper Language</p>'+
					'<ul>'+
						'<li class="eng"><span>ENG</span></li>'+
						'<li class="kor"><span>KOR</span></li>'+
					'</ul>'+
				'</div>';
				$(".movie-wrap .contents").append(_wp);
				$(".movie-wrap .movie-holder").css("display","block");
				$(".movie-wrap").addClass("open wpl");

				createWhitePaper();

				break;
              case "yp":
                var _wp='<div class="ypaper">'+
                  '<p class="subTitle">Yellowpaper</p>'+
                  '<ul>'+
                    '<li class=""><span class="label multiline">ICONstitution &amp;<br>Governance</span><span id="a-1" class="en">ENG</span><span id="a-2" class="kr">KOR</span></li>'+
                    /*'<li class=""><span class="label">IISS</span><span id="b-1" class="en">ENG</span><span id="b-2" class="kr">KOR</span></li>'+*/
                    '<li class=""><span class="label multiline">Transaction Fee and<br>SCORE Operation Policy</span><span id="c-1" class="en">ENG</span><span id="c-2" class="kr">KOR</span></li>'+

                  '</ul>'+
                '</div>';
                $(".movie-wrap .contents").append(_wp);
                $(".movie-wrap .movie-holder").css("display","block");
                $(".movie-wrap").addClass("open ypl");

                createYellowPaper();

                break;
			case "wl":

				break;
			case "ie":

				break;
		}
	});

	$(".gnb .order p").click(function(){
		$(".header-wrap .page li."+$(this).attr("class")).trigger("click");
	});

	$(".footer-wrap .wrap-holder .select span").click(function(){
		$(this).siblings(".layer").css("display","block");
	});

    $(".footer-wrap .wrap-holder .select .layer li").click(function() {
		var v = $(this).text();
		var p = $(this).closest('.select');
		$(this).siblings('li').removeClass('on');
        $(this).addClass('on');
        p.addClass('on');
        p.find('> span').text(v);
        p.find('option').removeAttr('selected');
        p.find('option[value="'+v+'"]').attr('selected', 'selected');
        p.find('.layer').css('display', '');
        checkSendMessage();
	});

	$("#acco0").accordionFx({
		_fullOpen:true,
		_isChild : true
	});
	if( $(".wrap .content-wrap").hasClass("home")){
		$("#rollPartner").rollFx({
			// _fullOpen:true
		});
	}
	if( $(".wrap .content-wrap").hasClass("member")){
		$("#acco1").accordionFx({
			_fullOpen:true
		});
	}

	if($(".wrap .content-wrap").hasClass("support")){
		$("#acco1").accordionFx({
			_fullOpen:true
		});
		naviFx();
	}

	$(".moving").viewFx({
		_isOne : 0,
		_delay:0.5,
		_view:["moving", "moving-r"]
	});
}

function createWhitePaper(){
	$(".wpaper li").click(function(){
		var path="/resources/whitepaper/"
		var url;
		switch( $(this).attr("class") ){
			case "eng":  url = "ICON-Whitepaper-EN-Draft.pdf";	break;
			case "kor":  url = "ICON-Whitepaper-KO-Draft.pdf";	break;
			case "chn":  url = "ICON-Whitepaper-EN-Draft.pdf";		break;
			case "jpn":  url = "ICON-Whitepaper-EN-Draft.pdf";		break;
		}
		window.open(path+url, '_blank');
	});
}

function createYellowPaper() {
	$(".ypaper li span").click(function(){
		var path="/resources/file/"
		var url;
		switch( $(this).attr("id") ){
			case "a-1":  url = "ICON_Yellowpaper_ICONstitution_and_Governance_EN_V1.0.pdf?v=180914";	break;
			case "a-2":  url = "ICON_Yellowpaper_ICONstitution_and_Governance_KO_V1.0.pdf";	break;
			/*case "b-1":  url = "ICON-Whitepaper-EN-Draft.pdf";	break;
			case "b-2":  url = "ICON-Whitepaper-EN-Draft.pdf";	break;*/
			case "c-1":  url = "ICON_Yellowpaper_Transactionfee_EN_V1.0.pdf";	break;
			case "c-2":  url = "ICON_Yellowpaper_Transactionfee_KO_V1.0.pdf?v=180918";	break;
		}
		window.open(path+url, '_blank');
	});
}

function naviFx(){
	$(".navi .marginC li").click(function(){
		var _index = $(this).index();
		$("body, html").animate({
			scrollTop: $(" .screen1 .list li:eq("+_index+")").offset().top-80
		}, {duration : 800, easing: 'easeInOutQuad'});

		if( !$(" .screen1 .list li:eq("+_index+") .title").hasClass("on") ) {
			$(" .screen1 .list li:eq("+_index+") .title").trigger("click");
		}

	});
}

function createLanguage(){
	$(".language").hover(
		function(){
			$("ul", this).slideDown(150);
		},
		function(){
			$("ul", this).slideUp(150);
		}
	);
}

function accorClick($id, $index, $isOpen){
	$("#"+$id + " li:eq("+$index+") em" ).text( $isOpen ? "-":"+");
}

function checkSendMessage() {
	var w = $('.footer-wrap .sm'), s = w.find('.select > span');
	
	w.find('input').each(function() {
		if(checkEmpty($(this).val()) === '') {
			$(this).val('');
		}
	});
	
	if(s.text() != 'Subject' && $('input[name="name"]').val() != '' && $('input[name="email"]').val() != '' && $('input[name="message"]').val() != '') {
		w.find('#btnSendMessage').removeAttr('disabled');
	} else {
		w.find('#btnSendMessage').attr('disabled', 'disabled');
	}
}

function sendMessage() {
    var $name = $("input[name='name']");
    var $email = $("input[name='email']");
    var $message = $("input[name='message']");
    var $cate = $('select[name="category"]').val();

    if(!checkMail($email.val())) {
    	if($('html').attr('lang') == 'ko') {
    		alert('鞓皵毳� 鞚措鞚� 欤检唽毳� 鞛呺牓頃橃劯鞖�.');
    	} else {
    		alert('Please enter valid email address.');
    	}
    	$email.focus();
    	
    	return false;
    }
    
    var data = {
        name: $name.val(),
        email: $email.val(),
        subject: '[iCON WEB :: '+$cate+'] '+$name.val()+'雼橃澊 氅旍嫓歆€毳� 氚滌啞頃橃榾鞀惦媹雼�.',
        description: $message.val(),
        // requester_id: $email.val(),
        "priority": 1,
        "status": 2
    };

    $.ajax({
      url: "https://helloiconworld.freshdesk.com/api/v2/tickets",
      beforeSend: function (xhr) {
        xhr.setRequestHeader("Authorization", "Basic " + btoa("hYEyOouQvNiiyDgOqdBo" + ":" + "sdf"));
      },
      processData: false,
      data: JSON.stringify(data),
      type: 'POST',
      contentType: 'application/json',
      success: function (data) {
        console.log(data);
        if($('html').attr('lang') == 'ko') {
    		alert('氅旍嫓歆€ 鞝勳啞鞚� 鞕勲頄堨姷雼堧嫟.');
    	} else {
    		alert('Sent message complete.');
    	}
        $name.val('');
        $email.val('');
        $message.val('');
        $('.footer-wrap .sm .select').removeClass('on');
        $('.footer-wrap .sm .select .layer li').removeClass('on');
        $('.footer-wrap .sm .select > span').text('Subject');
        $('#btnSendMessage').attr('disabled', 'disabled');
      },
      error: function (error) {
        console.dir(error);
      }
    });
}

$(document).ready(function(){
	var init = function(){}

	$(document).mouseup(function(e){
		var container = $(".footer-wrap .wrap-holder .layer");
		if(container.has(e.target).length===0){
			container.css("display","none");
		}
	});

	loadFx();
	// createMenu();

	$(window).scroll(function(){
		scrollFx();
	});

	createBtn();
	
	var _menuKey = sessionStorage.getItem("menu");
	if(_menuKey === 'open') {
		$(".root").addClass( "open" );
		_now = -1*_gnbW;
		$(this).css({'transform':'matrix(1,0,0,1,'+_now+',0)',
					'-webkit-transform':'matrix(1,0,0,1,'+_now+',0)',
					'-moz-transform':'matrix(1,0,0,1,'+_now+',0)'
		});

		screenResizeFx(_now);
	}
});
$(window).load(function(){
	$( window ).resize(function() {
		loadFx();
	});
	createMenu();
});


$(window).ready(function(){
	$(".movie-wrap .btnClose").on('click',function(){
		$(".movie-wrap").removeClass("wpl");
		$(".movie-wrap").removeClass("open");
		$('.movie-wrap .contents').empty();
		$(".movie-wrap .movie-holder").css("display","none");
		$("body").css("overflow", "auto");

		$(".wpaper li").off();
	});
	
	$('.system-ready').on('click', function() {
		if($('html').attr('lang') == 'ko') {
    		alert('靹滊箘鞀� 欷€牍� 欷戩瀰雼堧嫟.');
    	} else {
    		alert('Preparing service.');
    	}
	});
});